<template>
  <el-dialog :model-value="props.show" :title="`${title}会员分层`" width="440px" :before-close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="分层名称" prop="name">
        <el-input style="width: 80%;" v-model="form.name" placeholder="请输入会员分层名称"></el-input>
      </el-form-item>
      <div style="fontSize:14px;margin-bottom:16px;color:#000">创建人群<span style="color:#18BF5B">同时满足</span>以下条件</div>
      <el-form-item label="消费时间" :prop="form.consumptionTime === 1 ? 'intervalConsumption' : 'consumptionTime'">
        <div class="flex">
          <el-radio-group v-model="form.consumptionTime" @change="consumptionTimeChange">
            <el-radio :label="0">累计消费</el-radio>
            <el-radio :label="1">区间消费</el-radio>
          </el-radio-group>
          <div class="flex intervalConsumption" v-if="form.consumptionTime === 1">
            近 <el-input style="width:80px;margin:0 8px" v-model.number="form.intervalConsumption"
              @input="(val) => inputChange(val, 'intervalConsumption', form, 1, 300)"></el-input> 天
          </div>
        </div>
      </el-form-item>
      <el-form-item label="消费情况" prop="consumptionSituation">
        <div>
          <el-checkbox-group v-model="consumptionSituationOptions">
            <el-checkbox label="消费金额" />
            <el-checkbox label="消费次数" />
            <el-checkbox label="核销次数" />
          </el-checkbox-group>
          <el-form ref="formRef1" :model="form.consumptionSituation">
            <div class="flex consumptionSituationInputBox" v-for="item in consumptionSituationOptions" :key="item">
              <span>{{ item }}</span>
              <el-form-item :prop="consumptionSituationKeys[item] + 'Conditions'"
                :rules="[{ required: true, trigger: 'change', message: '请选择' }]">
                <el-select v-model="form.consumptionSituation[consumptionSituationKeys[item] + 'Conditions']"
                  class="mySelect">
                  <el-option v-for="condition in conditions" :key="condition" :label="condition" :value="condition" />
                </el-select>
              </el-form-item>
              <el-form-item :prop="consumptionSituationKeys[item] + 'Num'" :rules="getRules('input', '')">
                <el-input-number placeholder="请输入" v-if="item === '消费金额'" :precision="2" :min="0.01" :max="999999.99"
                  class="myNumberInput" v-model="form.consumptionSituation[consumptionSituationKeys[item] + 'Num']" />
                <el-input-number placeholder="请输入" class="myNumberInput" v-else :min="1" :max="9999"
                  v-model="form.consumptionSituation[consumptionSituationKeys[item] + 'Num']" />
              </el-form-item>

              <span>{{ item === '消费金额' ? '元' : '次' }}</span>
            </div>
          </el-form>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="loading" @click="handleClose">取消</el-button>
        <el-button :loading="loading" type="primary" @click="confirm(formRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { useTableRefresh } from '@/hooks';
import { useMemberLayering } from '../Hooks/index'
import { memberLayeringAction } from '@/api/Member/index'
import getRules from '@/validUtils/index'
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  detail: {
    type: Object,
    default: () => { },
  },
});
const isEdit = computed(() => {
  return Object.keys(props.detail).length > 0;
});
const title = computed(() => {
  return isEdit.value ? '编辑' : '新增';
});
const {
  seachTableRef
} = useMemberLayering();

const conditions = ['>', '<', '=', '>=', '<=']
const rules = ref({
  name: [
    { required: true, message: '请输入会员等级名称', trigger: 'blur' },
  ],
  consumptionTime: [
    { required: true, message: '请选择消费时间', trigger: 'blur' },
  ],
  consumptionSituation: [
    { required: true, message: '请选择消费情况', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!consumptionSituationOptions.value.length) return callback('请选择消费情况');
        callback();
      }, trigger: 'change'
    },
  ],
  intervalConsumption: [
    { required: true, message: '请输入消费区间天数', trigger: 'blur' },
  ]
});
const form = ref({
  name: '',
  consumptionTime: 0,
  intervalConsumption: null,
  consumptionSituation: {
    amountConsumptionNum: null,
    amountConsumptionConditions: '',
    consumptionFrequencyNum: null,
    consumptionFrequencyConditions: '',
    numberWriteOffsNum: null,
    numberWriteOffsConditions: '',
  }
});
const consumptionSituationKeys = {
  '消费金额': 'amountConsumption',
  '消费次数': 'consumptionFrequency',
  '核销次数': 'numberWriteOffs'
}
/**
 * situationType	消费情况类型 1: 消费金额 2: 消费次数 3: 核销次数
 */
const situationTypes = {
  1: '消费金额',
  2: '消费次数',
  3: '核销次数'
}
watch(() => props.detail, (newVal) => {
  if (Object.keys(newVal).length) {
    form.value.name = newVal.layeringName
    form.value.consumptionTime = newVal.consumptionDays > 0 ? 1 : 0
    form.value.intervalConsumption = newVal.consumptionDays > 0 ? newVal.consumptionDays : null
    consumptionSituationOptions.value = newVal.conditionList.map(item => {
      return situationTypes[item.situationType]
    })
    for (const item of newVal.conditionList) {
      if (item.situationType === 1) {
        form.value.consumptionSituation.amountConsumptionNum = item.consumptionSituation
        form.value.consumptionSituation.amountConsumptionConditions = item.operationalConditions
      }
      if (item.situationType === 2) {
        form.value.consumptionSituation.consumptionFrequencyNum = item.consumptionSituation
        form.value.consumptionSituation.consumptionFrequencyConditions = item.operationalConditions
      }
      if (item.situationType === 3) {
        form.value.consumptionSituation.numberWriteOffsNum = item.consumptionSituation
        form.value.consumptionSituation.numberWriteOffsConditions = item.operationalConditions
      }
    }
  }else{
    resetForm()
  }
})

const loading = ref(false);
const formRef = ref();
const formRef1 = ref();
const consumptionSituationOptions = ref([]);

const consumptionTimeChange = (val) => {
  if (val === 0) {
    form.value.intervalConsumption = null;
    formRef.value.clearValidate();
  }
}
const inputChange = (val, key, data, min = 0, max = 9999) => {
  const reg = /^[0-9]*$/;
  if (!reg.test(val)) {
    data[key] = null;
  }
  if (+val < min) {
    data[key] = null;
  }
  if (+val > max) {
    data[key] = max;
  }
}
const filterSituationType = {
  "amountConsumption": 1,
  "consumptionFrequency": 2,
  "numberWriteOffs": 3
}
const confirm = async (formEl) => {
  if (!formEl) return;

  await formEl.validate(async (valid) => {
    await formRef1.value.validate(async (valid1) => {
      try {
        loading.value = true;
        if (!valid || !valid1) return;
        const params = {
          layeringName: form.value.name,
          consumptionDays: form.value.consumptionTime ? form.value.intervalConsumption : 0,
          conditionList: consumptionSituationOptions.value.map(item => {
            const key = consumptionSituationKeys[item]
            return {
              situationType: filterSituationType[key],
              consumptionSituation: form.value.consumptionSituation[key + 'Num'],
              operationalConditions: form.value.consumptionSituation[key + 'Conditions']
            }
          })
        };
        if (isEdit.value) {
          params.id = props.detail.id;
        }
        await memberLayeringAction(params);
        ElMessage.success(isEdit.value ? '修改成功' : '新增成功');
        useTableRefresh(seachTableRef, true)
        handleClose();
        resetForm();
      } finally {
        loading.value = false;
      }
    })
  });
}

const emit = defineEmits(['close']);
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  consumptionSituationOptions.value = [];
  form.value.name = '';
  form.value.consumptionTime = 0;
  form.value.intervalConsumption = null;
  form.value.consumptionSituation = {
    amountConsumption: {
      num: null,
      conditions: ''
    },
    consumptionFrequency: {
      num: null,
      conditions: ''
    },
    numberWriteOffs: {
      num: null,
      conditions: ''
    }
  }
}
const handleClose = () => {
  emit('close', false);
};
</script>

<style lang="less" scoped>
.flex {
  display: flex;
  justify-content: space-between;
}

.intervalConsumption {
  margin-left: 8px;
}

.consumptionSituationInputBox {
  margin-top: 16px;
}

.myNumberInput {
  width: 100px;

  :deep(.el-input-number__decrease) {
    display: none;
  }

  :deep(.el-input-number__increase) {
    display: none;
  }

  :deep(.el-input__wrapper) {
    padding: 1px 11px;
  }
}

.mySelect {
  width: 100px;

  // margin-left: 8px;
  :deep(.el-input__wrapper input) {
    text-align: center;
  }
}
</style>